package com.vastcom.web.controller;

import com.vastcom.exception.UsernameIsExitedException;
import com.vastcom.model.User;
import com.vastcom.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;


    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello world";
    }

    @GetMapping("/userList")
    public Map<String,Object> userList(){
        List<User> users=userRepository.findAll();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("users",users);
        return map;
    }


    @PostMapping("/signup")
    public User signUp(@RequestBody User user){
      User bizUser=userRepository.findByUsername(user.getUsername());
      if(bizUser!=null){
     throw new UsernameIsExitedException("用户名已存在");
      }
      user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
      return userRepository.save(user);
    }


}
